package com.idea.relax.tool.core.excel.easyexcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.idea.relax.tool.core.DateUtil;
import org.apache.commons.codec.Charsets;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @className: ExcelUtils
 * @description:
 * @author: salad
 * @date: 2022/2/17
 **/
public class ExcelUtils {

    private static final String SUF_XLS = ".xls";
    private static final String SUF_XLSX = ".xlsx";

    public static <T> void export(HttpServletResponse response, List<T> dataList, Class<T> clazz)
            throws IOException {
        try {
            export(response, DateUtil.format(LocalDateTime.now(),
                    "yyyyMMddHHmmss"), "导出数据", dataList, clazz);
        } catch (Throwable e) {
            throw e;
        }
    }

    public static <T> void export(HttpServletResponse response,
                                  String fileName, String sheetName,
                                  List<T> dataList, Class<T> clazz) throws IOException {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding(Charsets.toCharset("UTF-8").name());
            fileName = URLEncoder.encode(fileName, Charsets.toCharset("UTF-8").name());
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + SUF_XLS);
            EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(dataList);
        } catch (Throwable e) {
            throw e;
        }
    }

    public static <T> void importSave(MultipartFile file, Class<T> clazz, Importer<T> importer) {
        importSave(file, clazz, 0, importer);
    }

    public static <T> void importSave(MultipartFile file, Class<T> clazz, int sheetNo, Importer<T> importer) {
        try {
            ExcelReader excelReader = EasyExcel.read(new BufferedInputStream(file.getInputStream()),
                    clazz, new ImportListener(importer)).build();
            ReadSheet readSheet = EasyExcel.readSheet(sheetNo).build();
            excelReader.read(readSheet);
            excelReader.finish();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
